package com.itheima.stock.service.impl;

import com.itheima.stock.mapper.SysPermissionMapper;
import com.itheima.stock.mapper.SysRolePermissionMapper;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.mapper.SysUserRoleMapper;
import com.itheima.stock.pojo.domain.PermissionsTreeDomain;
import com.itheima.stock.pojo.entity.SysPermission;
import com.itheima.stock.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public List<SysPermission> getPermissionByUserId(Long userId) {
//        log.info("调用了一次getPermissionByUserId接口");
        //查找用户的角色集合
        List<Long> roleIds = sysUserRoleMapper.selectByUserId(userId);
        //查找角色对应的权限集合
        List<Long> permissionIds = sysRolePermissionMapper.selectByRoleIds(roleIds);
        List<SysPermission> sysPermissions = sysPermissionMapper.selectByIds(permissionIds);
        //排除重复的权限 根据title+url作为键来排除重复信息,并分类
        Map<String,Boolean> vis = new HashMap<>();
        List<SysPermission> contents = new ArrayList<>();
        for(int i=0;i<sysPermissions.size();++i){
            SysPermission sysPermission = sysPermissions.get(i);
            String key = sysPermission.getPerms()+sysPermission.getName();
            if(vis.containsKey(key)){
                continue;
            }else{
                vis.put(key,true);
                contents.add(sysPermission);
            }
        }
        return contents;
    }


    public List<PermissionsTreeDomain> getPermissionTree(List<SysPermission> permissions,Long pid,Boolean isOnlyMenuType){
        List<SysPermission> collect = permissions.stream()
                .filter(item -> Long.compare(item.getPid(), pid) == 0 && (isOnlyMenuType ? item.getType() != 3 && item.getCode().equals("") : true))
                .collect(Collectors.toList());
        List<PermissionsTreeDomain> collect2 = new ArrayList<>();
        for(int i=0;i<collect.size();++i){
            PermissionsTreeDomain permissionsTreeDomain = new PermissionsTreeDomain();
            BeanUtils.copyProperties(collect.get(i),permissionsTreeDomain);
            permissionsTreeDomain.setPath(collect.get(i).getUrl());
            permissionsTreeDomain.setChildren(getPermissionTree(permissions,permissionsTreeDomain.getId(),isOnlyMenuType));
            collect2.add(permissionsTreeDomain);
        }
        return collect2;
    }
}
